var wc = require("../components/winLocation.js")
import {
    initView
} from '../views/orderDetailView.js';
import {
    Logout
} from '../components/logout.js';
var logoutObject;

var token, loginName, openid, loginType, trans_seq, orderId, goodsAmount;
var refundsType = "01"; // 01 正常退货 1 非免息退货
var measurementAmount = 0; // 非免息退金额
var partialNum;   // 部分退货金额
var settlement_amt; // 原结算金额
var trans_amt; // 分期金额
var partInterest;  // 退货手续费
var isOpenday = "0";  // 0:非工作日  1：工作日
var trans_type = "";  // 可执行交易方式 撤销 || 退货
var serial_no = '';   // 订单串号
$(document).on("pageinit", "#orderDetail_page", controllerInit);

function controllerInit() {
    wc.checkBrowser();
    initValue();
    initView();
    getOrderData();
    $("#trans_t").on("touchend", function() {
        if($(this).hasClass("weui-btn weui-btn_plain-primary weui-btn_plain-disabled")){
          return;
        }else if(trans_type == "撤销"){
          $.confirm("是否撤销这笔交易", function(serial_no) {
            //点击确认后的回调函数
            rescission()
          }, function() {
          //点击取消后的回调函数
          });
        }else{ // 判断一下如果有非免息的 调showCostDialog 2017-08-24
          $.confirm("是否退回该笔订单", function(serial_no) {
            //点击确认后的回调函数
            refundsType = "01";
            measurementAmount = 0;
            returnGoods();
          }, function() {
          //点击取消后的回调函数
          });
        }

    });
    $("#cost-yes").on("touchend",function  () {
        $("#prompt-return_cost").fadeOut(200);
        refundsType = "02";
        returnGoods();
    });
    $("#partialReturn-button").on('touchend',partialReturnFnc)
    isWordDate();
}

// 请求订单
function getOrderData() {
    var oParameters = {
        "token": token,
        "bizLicNo": loginName,
        "loginName": loginName,
        "openid": openid,
        "loginType": loginType,
        "trans_seq": trans_seq
    }

    $.post(TransDetail_URL, oParameters, odback)
}

// 订单详情回调函数
function odback(odata) {
    if (odata.login_response) {
        haslogin(odata);
        return;
    }
    console.dir(odata);

    if (odata.tltdtrans_response && odata.tltdtrans_response.trans_info_arrays && odata.tltdtrans_response.trans_info_arrays.trans_info && odata.tltdtrans_response.trans_info_arrays.trans_info[0]) {

        var trans_info = odata.tltdtrans_response.trans_info_arrays.trans_info[0];
        var format_time = changeDateTime(String(trans_info.trans_date) + String(trans_info.trans_time),"second");
        var order_id_str = String(trans_info.order_id).replace("s","");
        orderId = order_id_str;
        goodsAmount = String(trans_info.goods_Amount).replace(",","");
        settlement_amt = String(trans_info.settlement_amt).replace(",","");
        trans_amt = String(trans_info.trans_amt).replace(",","");
        serial_no = trans_info.serial_no;
        $("#order-id").text(order_id_str);
        $("#trans_status").text(trans_info.trans_status);
        if(trans_info.trans_status == "交易失败"){
            $("#remarks-box").show();
            $("#remarks").text(trans_info.remarks);
        }else{
            $("#remarks-box").hide();
        }
        $("#trans_amt").text(trans_info.trans_amt);
        $("#order-time").text(format_time);
        $("#trans_type").text(trans_info.nt);
        $("#trans_t").text(trans_info.trans_type);
        trans_type = trans_info.trans_type;
        $("#term_id").text(trans_info.term_id);
        $("#goods_Amount").text(trans_info.goods_Amount);
        if(trans_info.refund_amt && trans_info.refund_amt != "null" && trans_info.refund_amt !=0 && trans_info.refund_amt !="undefine"){
            $("#refund_amt").text(trans_info.refund_amt)
        } else {
            $("#refund_amt-cell").hide()
        }
        $("#card_No").text(trans_info.credit_Card_No);
        if(trans_info.trans_type != "退货" && trans_info.trans_type != "撤销"){
            $("#trans_t").attr("class","weui-btn weui-btn_plain-primary weui-btn_plain-disabled");
        }
        $("#settlement_amt").text(trans_info.settlement_amt);
        $("#stage_count").text(trans_info.stage_count + "期");
        $("#rtngds_pay_amt").text(trans_info.rtngds_pay_amt);
        if(trans_info.trans_refund_type == '0'){
            $("#partialReturn-well").hide()
        }
    }
}

// 退货请求
function returnGoods() {
    var rgParameters = {
        "token": token,
        "loginName": loginName,
        "bizLicNo": loginName,
        "openid": openid,
        "loginType": loginType,
        "orderId": orderId,
        "refundsType": "01",
        "goodsAmount": goodsAmount
    };
    $.post(MerRefunds_URL, rgParameters, rgback);
}

//  退货回调函数
function rgback (rgdata) {
    if (rgdata.login_response) {
        haslogin(rgdata);
        return;
    }
    console.dir(rgdata);
    if(rgdata.lft_orderinfo_response && rgdata.lft_orderinfo_response.resp_code == "0000"){
        $.alert("退货申请成功");
    }else if(rgdata.lft_orderinfo_response && rgdata.lft_orderinfo_response.resp_code == "8888"){
        $.alert("退货成功");
    }else if(rgdata.lft_orderinfo_response && rgdata.lft_orderinfo_response.resp_code == "4009"){
        $.alert("该笔订单正在处理中，请稍后");
    }else{
        $.alert("退货失败");
    }
    getOrderData();
}


// 时间20161108160023 转为 2016-11-08 16:00:23
function changeDateTime(dateString, type) {
    var pattern = /(\d{4})(\d{2})(\d{2})/;
    var formatedDate;
    if (type == "time") {
        pattern = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/;
        formatedDate = dateString.substr(0, 12).replace(pattern, '$1-$2-$3 $4:$5');
    } else if (type == "second") {
        pattern = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/;
        formatedDate = dateString.substr(0, 16).replace(pattern, '$1-$2-$3 $4:$5:$6');
    } else if (type == "date") {
        formatedDate = dateString.substr(0, 8).replace(pattern, '$1-$2-$3');
    }

    return formatedDate;
}

// 判断是否有效登入
function haslogin(msg) {
    if (msg.login_response) {
        $.alert("该账户已在别的地方登录,请重新登入");
        setTimeout(function() {
            location.href = LoginInit_URL;
        }, 3000);
    }
}

// 初始化变量
function initValue() {
    wc.QueryString.Initial();
    trans_seq = wc.QueryString.GetValue("trans_seq");
    getSessionStorage();
    logoutObject = new Logout();
}

// 取本地存储essionStorage
function getSessionStorage() {
    token = sessionStorage.getItem("tltd_token");
    loginName = sessionStorage.getItem("tltd_loginName");
    openid = sessionStorage.getItem("tltd_openid");
    loginType = sessionStorage.getItem("tltd_loginType");
    console.log(token, loginName, openid, loginType);
}

// 部分退货按钮事件
function partialReturnFnc() {
    var iwh = isWorkHours();
    if(iwh) {
        $.modal({
          title: "退货申请",
          text: '<div class="weui-cells weui-cells_form" style="border-bottom-width: 0; margin-bottom: -0.7em;"><div class="weui-cell" style="padding: 5px 0;"><div class="weui-cell__hd" style="padding: 15px 0;"><label for="partialNum" class="weui-label" style="width: 80px;text-align: left;">退货金额</label></div><div class="weui-cell__bd"><input id="partialNum" class="weui-input"" placeholder="请输入金额"> </div> </div></div>',
          buttons: [
            { text: "提交", onClick: partialMeasure}
          ]
        });
    } else {
        $.alert("请在工作日8:00-14:00申请退货,感谢你的配合");
    }
}

// 调退货测算接口
function partialMeasure() {
    partialNum = $("#partialNum").val()
    if(isBigGoodsAmount(partialNum)){
        // 调测算接口
        var rgParameters = {
            "token": token,
            "loginName": loginName,
            "bizLicNo": loginName,
            "openid": openid,
            "loginType": loginType,
            "orderId": orderId,
            "refundsType": "01",
            "refundAmt": partialNum
        };
        console.log("调测算接口....")
        $.post(TransPartRefundTypeServlet_URL,rgParameters,function (csdata) {
            if(csdata.lfq_search_order_response && csdata.lfq_search_order_response.resp_code === "0000"){
                measureCallBack(csdata.lfq_search_order_response.partInterest)
            }else if(csdata.error_response && csdata.error_response.sub_msg){
              $.alert(csdata.lfq_search_order_response.sub_msg)
            }else if(csdata.lfq_search_order_response && csdata.lfq_search_order_response.resp_msg){
              $.alert(csdata.lfq_search_order_response.resp_msg)
            }
            console.dir(csdata)
        }).error(function(csdata){
            console.log("error",csdata)
        })

    }
}



// 测算接口回调函数
function measureCallBack(partInterest1) {
    partInterest = (parseFloat(partInterest1)/100).toFixed(2);
    var thdke = ((parseFloat(settlement_amt)*100 + parseFloat(partInterest1) - (parseFloat(trans_amt)*100-parseFloat(partialNum)*100))/100).toFixed(2)
    var textStr = `
    <div class="weui-cells" id="measure-cells" style="color: #222;text-align: right;">
      <div class="weui-cell">
        <div class="weui-cell__hd">
          <p>退款金额</p>
        </div>
        <div class="weui-cell__bd">${partialNum}元</div>
      </div>
      <div class="weui-cell">
        <div class="weui-cell__hd">
          <p>退款手续费</p>
        </div>
        <div class="weui-cell__bd">${partInterest}元</div>
      </div>
      <div class="weui-cell">
        <div class="weui-cell__hd">
          <p>退货打款额</p>
        </div>
        <div class="weui-cell__bd">${thdke}元</div>
      </div>
    </div>
    <div style="text-align: left;padding: 1em;line-height: 1.5em;font-size: 13px;">
      该笔订单已超过免费退货期，现在发起部分退货需退回结算款项及手续费共计人民币<span style="color: #2792e4;">${thdke}元</span>。请在当日14：30点前汇款至以下退款账户，失效后再次申请时，退货打款金额可能因为利息增加而不同
    </div>
    <div style="text-align: left;padding: 0 1em 1em 1em;line-height: 1.8em;font-size: 13px;color: #2792e4;">
      <div><span>账号名称:</span><span>通联商务服务有限公司</span></div>
      <div><span>银行名称:</span><span>中国建设银行南昌银都分理处</span></div>
      <div><span>银行账户:</span><span>36050153017200000039</span></div>
      <div><span>联 行 号:</span><span>1054210055484</span></div>
    </div>
    `
    $.modal({
      title: "退货确认",
      text: textStr,
      buttons: [
        { text: "取消", className: "default",onClick:function () {

        }},
        { text: "确认", onClick: function () {
            partialReturnGoods()
        }}
      ]
    });
    changeDialogType("measure-cells")
}

// 调部分退货接口
function partialReturnGoods() {
    // 调部分退货接口
    var rgParameters = {
        "token": token,
        "loginName": loginName,
        "bizLicNo": loginName,
        "openid": openid,
        "loginType": loginType,
        "orderId": orderId,
        "refundsType": "01",
        "goodsAmount":goodsAmount,
        "cancelInterest":partInterest,
        "refundAmt": partialNum
    };
    console.log("调测算接口....")
    $.post(MerDopeRefundsServlet_URL,rgParameters,function (csdata) {
        // 退货申请成功
        if(csdata.lft_orderinfo_response&& csdata.lft_orderinfo_response.resp_code =="0000"){
            var textmsg = "退货成功"
            if(csdata.lft_orderinfo_response.resp_msg.indexOf("等待审核") != -1){
              textmsg = '退货申请成功,等待商户确认'
            }
            $.alert({
              title: '申请提示',
              text: textmsg,
              onOK: function () {
                location.reload()
              }
            })
        }else{
            var msg = "退货失败"
            if(csdata.lft_orderinfo_response&& csdata.lft_orderinfo_response.resp_msg){
                msg += "," + csdata.lft_orderinfo_response.resp_msg;
            }
            $.alert(msg)
        }

    }).error(function(csdata){

        console.log("error",csdata)
    })
}


// 判断部分退货金额是否大于商品金额 符合条件
function isBigGoodsAmount(partialNum) {
    var isOk = true

    if(partialNum){
        partialNum = parseFloat(partialNum)
    }else{
        partialNum = 0
    }
    if(partialNum ==0 || partialNum>parseFloat(goodsAmount)){
        isOk = false
        $.confirm({
            title: '提示',
            text:"您输入的退货金额不合理,请重新输入退货金额",
            onOK:partialReturnFnc,
            onCancel:function () {
                console.log("2222222222222")
            }
        })
    }

    return isOk
}

/* -------------------------------------------
 撤销交易 --*/
 // 撤销交易
function rescission() {
    var rgParameters = {
        "token": token,
        "loginName": loginName,
        "bizLicNo": loginName,
        "openid": openid,
        "loginType": loginType,
        "orderId": orderId,
        "serial_no": serial_no
    };
    $.post(MerConsumeRevokeServlet_URL, rgParameters, rescissionsBack);
}

// 撤销交易回调函数
function rescissionsBack(rdata) {
  if(rdata.lft_orderinfo_response && rdata.lft_orderinfo_response.resp_code == "0000"){
    $.alert("撤销成功")
    getOrderData()
  }else if(rdata.lft_orderinfo_response && rdata.lft_orderinfo_response.resp_msg){
    $.alert("撤销交易失败," + rdata.lft_orderinfo_response.resp_msg)
  }else{
    $.alert("撤销交易失败")
  }
}

/*--------------------------------*/

// 判断时间是否在工作日8:00 - 14:00 返回布尔值
function isWorkHours() {
    $.post(LFQCreateOrderServlet,{"servlet_type": "query_openday"},function (wdata) {
        console.dir(wdata)
    })
    var nowTime = new Date();
    var nowHours = nowTime.getHours()
    var iwh = true;
    if(isOpenday == "0" || nowHours<8 || nowHours>13){
        iwh = false
    }
    return iwh;
}

// 判断服务器时间是否工作日
function isWordDate() {
    $.post(LFQCreateOrderServlet,{"servlet_type": "query_openday"},function (wdata) {
        if(wdata.openday_response && wdata.openday_response.isOpenday == "1"){
            isOpenday = "1"
        }
    })
}

// 调整弹框样式
function changeDialogType(contentId) {
    var contenId = '#'+contentId;
    var cdom = $(contenId);
    var weuidialogbd = $(contenId).parent(".weui-dialog__bd");
    var weuidialog = $(contenId).parent(".weui-dialog");
    weuidialogbd.css({"padding":"0 0 0.6em 0"});
    weuidialog.css({"width": "90%", "max-width": "350px"});
}
